//前台不登录就可以访问的接口
var express = require('express');
const formidable = require('formidable'); //处理含有文件上传的表单
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const random = require('string-random');
const { wechat } = require('../config/global');
const { Success, MError, Guest } = require("../utils/Result");// 封装统一接口返回方法
const Db = require("../utils/Db");
const { getUUID, getToken } = require("../utils");
const { checkToken, getuid } = require("../utils"); // 登录拦截中间件
const WXBizDataCrypt = require('../utils/Node/WXBizDataCrypt') //引入解密模块
var request = require('request'); //引入request模块

const { scheduleCronstyle } = require('../utils/msg.js');//推送、获取消息、定时任务方法
const tableName = 'message';//商品最新消息表
// var app = express();

// 引入发送短信模块（使用阿里云的短信）
const Core = require('@alicloud/pop-core');
const cookiesession = require('cookie-session');
const { type } = require('os');
const { log } = require('console');

var router = express.Router();
const tableNameCate = 'category';//商品分类
const tableNameBanner = 'banner';//轮播图
const tableNameGoods = 'goods';//商品
const tableNameSpecs = 'specs';//规格表
const tableNameMember = 'member';//会员表
const tableNameSeck = 'seckill';//限时秒杀表
const tableNameWXUser = 'member_ceshi';//微信登录测试使用
const tableNameCode = 'code';//微信登录测试使用
const tableNameOrder = 'shop_order'
const tableNameAddress = 'address'


//javascript  树形结构
function toTree(data) {
    // 删除 所有 children,以防止多次调用
    data.forEach(function (item) {
        delete item.children;
    });

    // 将数据存储为 以 id 为 KEY 的 map 索引数据列
    var map = {};
    data.forEach(function (item) {
        // 在该方法中可以给每个元素增加其他属性
        // item.text = item.name;
        if (item.pid == 0) {
            // console.log(item.pid)
            map[item.id] = item;
        }
    });
    // console.log(map);
    var val = [];
    data.forEach(function (item) {
        // 以当前遍历项的pid,去map对象中找到索引的id
        var parent = map[item.pid];
        // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
        if (parent) {
            //  添加到父节点的子节点属性中
            (parent.children || (parent.children = [])).push(item);
        } else {
            //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
            val.push(item);
        }
    });

    return val;
}

/**
 * 根据规格属性id获取规格相关数据
 * skuList: sku列表
 * sn: 规格属性id
 * num: 传一个不重复的数值即可
*/
async function getSkuInfoById(req, skuList, sn, num) {
    // 规格属性值信息: 规格属性值id和规格类目specsid
    const [{ specsid }] = await Db.select(req, `select * from specs_attr where id=${sn}`);
    // 规格类目信息: 比如 颜色, 尺码
    const [{ specsname }] = await Db.select(req, `select * from specs where id=${specsid}`);
    // 查询类目包含的规格属性: 比如 红色, XL
    const specsAttrs = await Db.select(req, `select * from specs_attr where specsid=${specsid}`);

    const treeItem = {
        k: specsname,
        k_s: `s${num}`,
        v: specsAttrs.map(({ id, specsval: name }) => {
            return { id, name }
        })
    }
    // console.log(treeItem,'specsname');

    // 规格-库存-价格
    const list = skuList.map(({ id, s1, s2, price, stock_num }) => {
        // 将价格单位转换为分
        return { id, s1, s2, price: price * 100, stock_num }
    });
    return {
        treeItem, list
    }
}

// 商品搜索
router.get('/search', async (req, res) => {
    const { keywords, page, size } = req.query;
    if (!keywords || !page || !size) {
        res.send(MError("缺少必要条件"));
        return;
    }
    const sql = `SELECT id,goodsname,price,market_price,img FROM ${tableNameGoods} WHERE goodsname like '%${keywords}%' limit ${(page - 1) * size},${size}`
    let goodsList = await Db.select(req, sql);
    const countSql = `select count(*) as total from ${tableNameGoods} where goodsname like '%${keywords}%'`;
    let countResult = await Db.select(req, countSql);

    res.send(Success({ total: countResult[0].total, goodsList: goodsList?goodsList:[] }));
})


//获取分类信息
router.get("/getcate", async (req, res) => {
    let data = await Db.select(req, `SELECT * FROM ${tableNameCate} WHERE pid = 0 AND status = 1`);
    res.send(Success(data));
});

// 获取所有商品分类数据 返回分类树（递归）
router.get("/getcates", async (req, res) => {
    let data = await Db.select(req, `SELECT * FROM ${tableNameCate} WHERE status = 1`);
    // const data = await Db.select(req, `SELECT a.*,b.id,b.goodsname,b.img FROM ${tableNameCate} a LEFT JOIN ${tableNameGoods} b ON a.id = b.second_cateid WHERE a.status = 1`);
    // console.log(data)
    // 将数据排序 父与子关系
    data = toTree(data)
    // console.log(data)
    res.send(Success(data));
});

//获取轮播图信息
router.get("/getbanner", async (req, res) => {
    let data = await Db.select(req, `SELECT id,second_cateid,title,img FROM ${tableNameBanner} WHERE status = 1`);
    // console.log(data)
    res.send(Success(data));
});

//获取限时秒杀
router.get("/getseckill", async (req, res) => {

    // 当天0点
    var start = new Date(new Date(new Date().toLocaleDateString()).getTime()).getTime();
    // console.log(start)
    // 当天23:59
    // var end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1000).getTime();
    // let sql = `SELECT a.*,b.img,b.price FROM ${tableNameSeck} a LEFT JOIN ${tableNameGoods} b ON a.goodsid = b.id WHERE begintime >= ${start} AND endtime <= ${end}`;
    // console.log(sql)
    let data = await Db.select(req, `SELECT a.*,b.img,b.price FROM ${tableNameSeck} a LEFT JOIN ${tableNameGoods} b ON a.goodsid = b.id WHERE endtime > ${start}`);
    res.send(Success(data));
})

//获取首页商品-推荐、最新上架、所有商品
router.get("/gethortgoods", async (req, res) => {
    let data1 = await Db.select(req, `SELECT id,goodsname,price,market_price,img FROM ${tableNameGoods} WHERE status = 1 AND ishot = 1 LIMIT 10`);
    let data2 = await Db.select(req, `SELECT id,goodsname,price,market_price,img FROM ${tableNameGoods} WHERE status = 1 AND isnew = 1 LIMIT 10`);
    let data3 = await Db.select(req, `SELECT id,goodsname,price,market_price,img FROM ${tableNameGoods} WHERE status = 1 LIMIT 10`);
    let data = [];
    data.push({ content: data1 });
    data.push({ content: data2 });
    data.push({ content: data3 });
    res.send(Success(data));
});

//获取分类下商品列表数据(支持分页)
router.get("/getgoodslist", async (req, res) => {
    const { page, size, cateid } = req['query'];
    if (!page || !size) {
        return res.send(MError("缺少必要条件"));
    }
    let where = '';
    // where = `WHERE status = 1  AND  second_cateid = ${cateid}`;
    if (cateid) {
        where += ` WHERE first_cateid=${cateid} `;
    }
    let sql = `SELECT id,second_cateid,goodsname,price,market_price,img FROM ${tableNameGoods} ${where}`;
    if (size && page) {
        let pagesize = (page - 1) * size;//设置偏移量
        sql += ` LIMIT ${pagesize},${size} `;
    }
    let goodsData = await Db.select(req, sql);
    // 获取总页数
    let countSql = `SELECT count(id) as count FROM ${tableNameGoods} ${where}`;
    console.log(countSql, 'countSql');
    let countNum = await Db.select(req, countSql);
    let total = Math.ceil(countNum[0].count / size);
    // 组装商品数据和总页码
    res.send(Success({ total: countNum[0].count, goodsData: goodsData ? goodsData : [] }));
});
//获取一条商品信息
router.get("/getgoodsinfo", async (req, res) => {
    const { id } = req['query'];
    if (!id) {
        res.send(MError("缺少必要条件"));
        return;
    }
    const info = await Db.select(req, `SELECT a.*,b.specsname FROM ${tableNameGoods} a LEFT JOIN ${tableNameSpecs} b ON a.specsid = b.id WHERE a.id = '${id}'`);
    if (info) {
        // 商品id
        const { id } = info[0];
        const sku = await Db.select(req, `select * from goods_sku where gid=${id}`);
        if (sku) {
            const { s1, s2 } = sku[0];

            // 规格属性值信息: 规格属性值id和规格类目specsid
            /*  const [{ specsid }] = await Db.select(req, `select * from specs_attr where id=${s1}`);
             // 规格类目信息: 比如 颜色, 尺码
             const [{ specsname }] = await Db.select(req, `select * from specs where id=${specsid}`);
             // 查询类目包含的规格属性: 比如 红色, XL
             const specsAttrs = await Db.select(req, `select * from specs_attr where specsid=${specsid}`);
             const tree = [
                 {
                     k: specsname,
                     k_s: 's1',
                     v: specsAttrs.map(({ id, specsval: name }) => {
                         return { id, name }
                     })
                 }
             ];
             // 规格-库存-价格
             const list = sku.map(({ id, s1: s1, price, stock_num }) => {
                 // 将价格单位转换为分
                 return { id, s1, price: price * 100, stock_num }
             });
             info[0].sku = {
                 tree, list
             } */
            const skuInfo = {
                tree: [],
                list: []
            }
            if (s1) {
                const { treeItem: treeItem1, list } = await getSkuInfoById(req, sku, s1, 1);
                skuInfo.tree.push(treeItem1);
                skuInfo.list = list;
            }
            if (s2) {
                const { treeItem: treeItem2, list } = await getSkuInfoById(req, sku, s2, 2);
                skuInfo.tree.push(treeItem2);
                skuInfo.list = list;
            }
            info[0].sku = skuInfo;
            console.log(skuInfo, 'skuInfo');
        }
    }
    res.send(Success(info, '获取成功'));
});


// 注册账号处理函数
const register = async (req, res) => {
    let { phone, password } = req['body'];
    const info = await Db.select(req, `SELECT * FROM ${tableNameMember} WHERE phone = '${phone}'`);
    if (info) {
        res.send(MError("手机号已存在，不能重复！"));
    } else {
        const randstr = random(5);
        password += randstr;
        password = crypto.createHash('md5').update(password).digest("hex");
        const result = await Db.insert(req, tableNameMember, {
            uid: getUUID(),
            phone,
            nickname: phone,
            password,
            avatarurl: "/uploads/tou.jpg",
            randstr,
            addtime: new Date().getTime(),
            status: 1//新注册
        });
        if (result) {
            return true;
        }
        return false;
    }
}


// 登录处理函数
const login = async (req, res) => {
    let { phone, password } = req['body'];
    if (!phone || !password) {
        res.send(MError("请填写手机号和密码"));
        return;
    }
    const checkResult = await Db.select(req, `SELECT * FROM ${tableNameMember} WHERE  phone = '${phone}'`)
    if (!checkResult) {
        // res.send(MError("用户信息不存在"));
        // 自动注册
        await register(req, res);
    }
    const result = await Db.select(req, `SELECT * FROM ${tableNameMember} WHERE  phone = '${phone}'`)
    const info = result[0];
    password += info.randstr;
    password = crypto.createHash('md5').update(password).digest("hex");
    if (password !== info.password) {
        res.send(MError("用户名密码错误"));
        return;
    }
    // 当用户登录时，直接获取登录时的token返给前端 ，有效时间为60秒
    let token = getToken(info['uid']);
    let data = {
        token, uid: info.uid, phone: info.phone, nickname: info.nickname, avatarurl: info.avatarurl
    }
    res.send(Success(data, '登录成功'));
}



//注册
router.post("/register", register);

//登录
router.post("/login", login);


// token实时校验接口
router.get('/checktoken', async (req, res) => {
    if (!req.headers.authorization) {
        res.send(MError([], "请设置请求头,并携带验证字符串"));   //500
    } else if (!await checkToken(req)) { // 过期  
        res.send(Guest([], "登录已过期或访问权限受限"));   //403
    } else {
        res.send(Success({}, "登录有效"));//给前台返回uid存储在本地缓存中  200
        res.end();
    }
});


module.exports = router;